/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedLineData, pickedVertexData } from '@amcax/base';
import { previewer } from '@app-cad/module';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { CurvedBaseCommand, CurvedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useState } from 'react';

type Direction = 1 | -1;

type FormData = {
  base?: pickedVertexData;
  curve?: pickedLineData;
  count: number;
  distance: number;
};

type Params = {
  base: string;
  curve: string;
  count: number;
  distance: number;
  direction: Direction;
};

function CmdCopyVertex({ title, onClose, props }: CurvedCmdDialogParams) {
  const initData: FormData = {
    count: 1,
    distance: 0,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      base: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      count: {
        title: '数量',
        type: 'number',
      },
      distance: {
        title: '距离',
        type: 'number',
        format: NumberInputFormat.Length,
      },
    },
  };

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props != null) {
      const params: Params = props.params;
      const { base, curve, count, distance, direction } = params;

      await initEditDependency([base, curve]);

      const curveObj = picker.generatePickObjByPickID(curve, {
        showArrow: true,
      }) as pickedLineData;

      if (direction === -1) {
        curveObj.assisObj.reverse();
      }

      setFormData({
        base: picker.generatePickObjByPickID(base) as pickedVertexData,
        curve: curveObj,
        count,
        distance,
      });
    }
  }, []);

  const isFormDataValid = () => {
    const { base, curve, count, distance } = formData;

    return (
      base != null &&
      curve != null &&
      count > 0 &&
      distance != null &&
      distance != 0
    );
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, confirmCommand, isLoading } =
    useCommand('cmd-copy-vertex', {
      onClose,
      finishDraw: checkAndFinishDraw,
      commandName: 'CopyVertex',
      editDxid: (props as any)?.dxid,
    });

  const execute = async (preview: boolean) => {
    const { base, curve, count, distance } = formData;

    const params = {
      base: base.vertexId,
      curve: curve.edgeId,
      count,
      distance,
      direction: curve.assisObj.isReversed ? -1 : 1,
    };

    confirmCommand(
      {
        a: params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      previewer.clear();
      return;
    }

    await execute(true);
  };

  return (
    <PickableCommandForm
      disabled={initingEdit}
      onClose={onClose}
      submitLoading={isLoading}
      title={title}
      schema={schema}
      onChange={(v) => {
        setFormData(v);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        base: {
          'ui:placeholder': '请输入参考点',
          'ui:autofocus': true,
        },
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:options': {
            showArrow: true,
            curveReversable: true,
            allowInfiniteLine: true,
          },
        },
      }}
      formData={formData}
      noValidate
      isFormDataValid={isFormDataValid()}
    />
  );
}

export const cmdCopyVertex: CurvedBaseCommand = {
  id: 'CmdCopyVertex',
  label: 'command.copy-vertex',
  icon: 'commands/curved/point-copy',
  help: {
    remark: 'tips.redo',
  },
  create: (label, onClose, props) => (
    <CmdCopyVertex
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
    />
  ),
};
